package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    private final SpecParamService paramService;

    public SpecGroupServiceImpl(SpecParamService paramService) {
        this.paramService = paramService;
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long id) {
        // 1.查询到规格组的集合 select * from tb_spec_group where category_id = ?
        List<SpecGroup> groupList = query().eq("category_id", id).list();
        // 2.转换为 SpecGroupDTO 集合
        List<SpecGroupDTO> groupDTOList = SpecGroupDTO.convertEntityList(groupList);

        // 3.查询param集合，把所有组的所有的参数一起查出来，就是根据分类id查询参数
        // select * from tb_spec_param where category_id = ?
        List<SpecParamDTO> list = paramService.queryParams(id, null, null);

        // 4.要把SpecParam分组，根据group_id分组，id一致的放到一个集合，形成一个Map：key是groupId，值是id一致的param集合
        Map<Long, List<SpecParamDTO>> paramMap = list.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        // 5.把参数放入group
        for (SpecGroupDTO groupDTO : groupDTOList) {
            // 根据groupId查询规格参数
            List<SpecParamDTO> params = paramMap.get(groupDTO.getId());
            // 存入group
            groupDTO.setParams(params);
        }
        // 返回
        return groupDTOList;
    }
}